import base64
import requests
from django.conf import settings


class Image(object):
    def __init__(self, data):
        # Gitee API 配置
        self.repo = "bowen-img"  # 仓库名称
        self.branch = "master"  # 分支
        self.gitee_token = settings.GITEE_TOKEN
        self.owner = settings.REPO_OWNER  # 用户名
        self.data = data


    def image(self):
        file_content = self.data.read()
        # Gitee API 请求体
        data = {
            "access_token": self.gitee_token,
            "message": f"Upload {self.data.name}",
            "content": base64.b64encode(file_content).decode("utf-8"),
            "branch": self.branch
        }
        # 上传到 的 URL
        gitee_api_url = f"https://gitee.com/api/v5/repos/{self.owner}/{self.repo}/contents/image/{self.data.name}"
        response = requests.post(gitee_api_url, data=data)  # 使用 requests.post
        return response
    def delete(self):
        scpath=self.data.split('/')[-1]
        # print(scpath)
        gitee_api_get=f"https://gitee.com/api/v5/repos/{self.owner}/{self.repo}/contents/image/{scpath}"
        #获取sha
        lj=requests.get(gitee_api_get)
        # 获取SHA值
        file_sha = lj.json().get('sha')
        # print(file_sha)
        data = {
            "access_token": self.gitee_token,
            "message": f"Delete {scpath}",
            "branch": self.branch,
            "sha":file_sha
        }
        #  URL
        gitee_api_url = f"https://gitee.com/api/v5/repos/{self.owner}/{self.repo}/contents/image/{scpath}"
        response = requests.delete(gitee_api_url, params=data)  # 使用 requests.delete
        return response